package us.icitap.commandcenter.ui.dispatcher;


import java.util.List;
import java.util.logging.Level;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import us.icitap.commandcenter.CommandCenterUI;
import us.icitap.commandcenter.business.Result;
import us.icitap.commandcenter.business.ejb.persistence.Call;
import us.icitap.commandcenter.business.ejb.persistence.Dispatcher;
import us.icitap.commandcenter.listeners.ManageCallListener;
import us.icitap.commandcenter.ui.custom.CustButton;
import us.icitap.commandcenter.ui.custom.CustVerticalLayout;
import us.icitap.commandcenter.ui.operator.CallForm;
import us.icitap.commandcenter.utils.HandleNotification;

import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.event.Action;
import com.vaadin.server.ThemeResource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.Runo;

public class DispatcherVerticalLayout extends CustVerticalLayout implements ManageCallListener {

	private Connection connection;
	private Session session;
	
	List<Dispatcher> dispatchers;
	
	private NewCallTable newCallTable;
	private StartedVerificationTable startedVerificationTable;
	private ClosedVerificationTable closedVerificationTable;
	
	private StartVerificationWindow startVerificationWindow;
	private CloseVerificationWindow closeVerificationWindow;
	private UpdateVerificationWindow updateVerificationWindow;
	private UniqueNumberWindow uniqueNumberWindow;
	
	
	static final Action ADD_INFO = new Action("Shto te dhenat mbi telefonaten");
    static final Action CLOSE_CALL = new Action("Mbyll telefonate");
    
    static final Action CREATE_UN =  new Action("Krijo numrin unik");
    
	
    private final CustButton newCallButton = new CustButton();
    private  Window newCallWindow = null;
    
	public DispatcherVerticalLayout() {
		this.setMargin(true);
		
		final SelectDispatcherWindow window = new SelectDispatcherWindow(this);
		CommandCenterUI.getCurrent().addWindow(window);
		
		this.newCallButton.setIcon(new ThemeResource("img/icons/blue/Plus.png"));
		this.newCallButton.setStyleName(Runo.BUTTON_LINK);
		this.newCallButton.setDescription("<b>Hapet dritarja per te rregjistruar nje telefonate te re</b>");
		this.setSpacing(true);
		
	}
	

	public void startListening(){
	    try
	    {
	      connection = CommandCenterUI.appStatelessBean.getConnectionFactory().createConnection();
	      session= connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

	      Destination dest;
	      for (Dispatcher dispatcher : this.dispatchers) {
			dest  = session.createTopic("DISP" + dispatcher.getId().toString());
			MessageConsumer mc = session.createConsumer(dest);
			mc.setMessageListener(this.newCallTable);
	      }

	      connection.start();

	    }
	    catch (JMSException e)
	    {
	      e.printStackTrace();
	    }
	   
	}

	public void setDispatchers(List<Dispatcher> dispatchers){
		this.dispatchers = dispatchers;
		
		final HorizontalLayout hl = new HorizontalLayout();
		hl.setSizeUndefined();
		this.newCallTable = new NewCallTable(this.dispatchers.size()==1);
		Result<List<Call>> result = CommandCenterUI.appStatelessBean.getInitialNewCallList(this.dispatchers);
		if(result.isSucceeded())
			this.newCallTable.addCallToTable(result.getObject());
		else
			HandleNotification.showErrorOnScreen(result.getMessage());
		
		
		hl.addComponent(this.newCallTable);
		
		
		hl.addComponent(this.newCallButton);
		hl.setComponentAlignment(this.newCallButton, Alignment.TOP_LEFT);
		
		this.addComponent(hl);
		
		this.startedVerificationTable = new StartedVerificationTable(this.dispatchers.size()==1);
		result = CommandCenterUI.appStatelessBean.getWvCallList(this.dispatchers);
		if(result.isSucceeded())
			this.startedVerificationTable.addCallToTable(result.getObject());
		else
			HandleNotification.showErrorOnScreen(result.getMessage());
		
		this.addComponent(this.startedVerificationTable);
		
		
		this.closedVerificationTable = new ClosedVerificationTable(this.dispatchers.size()==1);
		result = CommandCenterUI.appStatelessBean.getClosedCallList(this.dispatchers);
		if(result.isSucceeded())
			this.closedVerificationTable.addCallToTable(result.getObject());
		else
			HandleNotification.showErrorOnScreen(result.getMessage());
		
		this.addComponent(this.closedVerificationTable);

		this.newCallButton.addClickListener(new ClickListener() {
			
			@Override
			public void buttonClick(ClickEvent event) {
				DispatcherVerticalLayout.this.newCallWindow  = new Window("Rregjistrimi i nje telefonate te re");
				DispatcherVerticalLayout.this.newCallWindow.setResizable(false);
				DispatcherVerticalLayout.this.newCallWindow.center();
				DispatcherVerticalLayout.this.newCallWindow.setModal(true);
				CallForm callForm = new CallForm(DispatcherVerticalLayout.this);
				DispatcherVerticalLayout.this.newCallWindow.setContent(callForm);
				CommandCenterUI.getCurrent().addWindow(DispatcherVerticalLayout.this.newCallWindow);
				
				
			}
		});
			
		newCallTable.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				Property prop = event.getProperty();
				if(prop.getValue() != null){
					Call call = (Call)prop.getValue();
					if(startVerificationWindow == null) 
						startVerificationWindow = new StartVerificationWindow(DispatcherVerticalLayout.this, call);
					else
						startVerificationWindow.setCall(call);
					CommandCenterUI.getCurrent().addWindow(startVerificationWindow);
				}
				
				
			}
		});
		
		startedVerificationTable.addActionHandler(new Action.Handler() {
            public Action[] getActions(Object target, Object sender) {
               if(target == null) return null;
               return new Action[]{ADD_INFO, CLOSE_CALL};
               
            }
            
            public void handleAction(Action action, Object sender, Object target) {
            	Call call = (Call) target;
            	
            	System.out.println("ACTION");
            	System.out.println(call.getVerificationNotes());
            	if (ADD_INFO == action) {
            		if(updateVerificationWindow == null) 
            			updateVerificationWindow = new UpdateVerificationWindow(DispatcherVerticalLayout.this, call);
					else
						updateVerificationWindow.setCall(call);
					
					CommandCenterUI.getCurrent().addWindow(updateVerificationWindow);
                }
                else if (CLOSE_CALL == action) {
                	if(closeVerificationWindow == null) 
						closeVerificationWindow = new CloseVerificationWindow(DispatcherVerticalLayout.this, call);
					else
						closeVerificationWindow.setCall(call);
					
					CommandCenterUI.getCurrent().addWindow(closeVerificationWindow);
                }

        }});
			
		closedVerificationTable.addActionHandler(new Action.Handler() {
			
			@Override
			public void handleAction(Action action, Object sender, Object target) {
				Call call = (Call) target;
				if(CREATE_UN == action){
					if(uniqueNumberWindow == null)
						uniqueNumberWindow = new UniqueNumberWindow(DispatcherVerticalLayout.this, call);
					else
						uniqueNumberWindow.setCall(call);
					
					CommandCenterUI.getCurrent().addWindow(uniqueNumberWindow);
				}
				
			}
			
			@Override
			public Action[] getActions(Object target, Object sender) {
				 if(target == null) return null;
	               return new Action[]{CREATE_UN};
			}
		});
		
		String dispatcherNames = "";
		
		for (Dispatcher dispatcher : dispatchers) {
			dispatcherNames += ", " + dispatcher.getName();
		}
		dispatcherNames = dispatcherNames.replaceFirst(",", "");
		Label l = new Label(dispatcherNames);
		this.addComponent(l);
			
		this.startListening();
	}

	@Override
	public void startCallVerification(Call call) {
		Result<Call> result = CommandCenterUI.appStatelessBean.startVerification(call);
		if(result.isSucceeded()){
			newCallTable.removeCallFromTable(call);
			startedVerificationTable.addCallToTable(call);
			this.startVerificationWindow.close();
			HandleNotification.showInfoOnScreen("Telefonata eshte ne pritje te verifikimit");
		}
		else {
			HandleNotification.showErrorOnScreen(result.getMessage());
		}

	}


	@Override
	public void updateCallInformation(Call call) {
		Result<Call> result = CommandCenterUI.appStatelessBean.updateCallInformation(call);
		if(result.isSucceeded()){
			startedVerificationTable.updateCall(result.getObject());
			this.updateVerificationWindow.close();
			HandleNotification.showInfoOnScreen("Telefonata vazhdon te verifikohet");
		}
		else
			HandleNotification.showErrorOnScreen(result.getMessage());
	}


	@Override
	public void closeCallVerification(Call call) {
		Result<Call> result = CommandCenterUI.appStatelessBean.closeVerification(call);
		if(result.isSucceeded()){
			startedVerificationTable.removeCallFromTable(call);
			closedVerificationTable.addCallToTable(call);
			this.closeVerificationWindow.close();
			HandleNotification.showInfoOnScreen("Veirifikim i telefonates perfundoi");
		}
		else
			HandleNotification.showErrorOnScreen(result.getMessage());
	}

	

	@Override
	public void generateUniqueNumber(Call call) {
		Result<Call> result = CommandCenterUI.appStatelessBean.generateUniqueNumber(call);
		if(result.isSucceeded()){
			closedVerificationTable.updateCall(call);
			this.uniqueNumberWindow.close();	
		}
		else
			HandleNotification.showErrorOnScreen(result.getMessage());
	}


	@Override
	public void addNewCall(Call call) {
		Result<Call> result = CommandCenterUI.appStatelessBean.addNewCall(call, false);
		if(result.isSucceeded()){
			newCallTable.addCallToTable(result.getObject());
			this.newCallWindow.close();
		}
		else
			CommandCenterUI.LOG.logp(Level.SEVERE, "CallForm", "actYes", result.getMessage());	
	}

	
	@Override
	public void detach() {
		CommandCenterUI.LOG.info("DispatcherVerticalLayout.detach()");
		try {
			if(session != null) session.close();
		    if(connection != null) connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
		super.detach();
	}
}
